{% extends 'assets/base.html' %}
{% load static %}

{% block title %}高级搜索{% endblock %}

{% block extra_css %}
<style>
.search-builder {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}

.condition-row {
    background: white;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    padding: 15px;
    margin-bottom: 10px;
    position: relative;
}

.condition-row:hover {
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.remove-condition {
    position: absolute;
    top: 10px;
    right: 10px;
    color: #dc3545;
    cursor: pointer;
}

.remove-condition:hover {
    color: #c82333;
}

.logic-operator {
    text-align: center;
    margin: 10px 0;
    font-weight: bold;
    color: #007bff;
}

.search-results {
    margin-top: 20px;
}

.result-item {
    border: 1px solid #e9ecef;
    border-radius: 6px;
    padding: 15px;
    margin-bottom: 10px;
    background: white;
    transition: all 0.2s ease;
}

.result-item:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    transform: translateY(-1px);
}

.search-history-item {
    cursor: pointer;
    padding: 8px 12px;
    border-radius: 4px;
    margin-bottom: 5px;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
}

.search-history-item:hover {
    background: #e9ecef;
}

.quick-actions {
    position: sticky;
    top: 20px;
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 15px;
}

.field-type-indicator {
    font-size: 0.8em;
    color: #6c757d;
    margin-left: 5px;
}

.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 面包屑导航 -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
            <li class="breadcrumb-item active" aria-current="page">高级搜索</li>
        </ol>
    </nav>

    <!-- 页面标题和操作按钮 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <h2 class="mb-0">
                    <i class="fas fa-search-plus me-2 text-primary"></i>高级搜索
                </h2>
                <div class="btn-group">
                    <button type="button" class="btn btn-outline-secondary" onclick="clearSearch()" title="清空所有搜索条件">
                        <i class="fas fa-eraser me-1"></i>清空
                    </button>
                    <button type="button" class="btn btn-success" onclick="executeSearch()" title="执行当前搜索条件">
                        <i class="fas fa-search me-1"></i>执行搜索
                    </button>
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" title="更多搜索功能">
                            <i class="fas fa-ellipsis-v"></i>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#" onclick="saveAsTemplate()">
                                <i class="fas fa-save me-2"></i>保存为模板
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="saveSearch()">
                                <i class="fas fa-bookmark me-2"></i>保存搜索
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" onclick="showSearchHelp()">
                                <i class="fas fa-question-circle me-2"></i>搜索帮助
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="showSearchTemplates()">
                                <i class="fas fa-layer-group me-2"></i>搜索模板
                            </a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- 搜索构建器 -->
        <div class="col-md-8">
            <div class="search-builder">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">搜索模型</label>
                        <select id="searchModel" class="form-select" onchange="onModelChange()">
                            <option value="">请选择搜索模型</option>
                            {% for key, model in search_models.items %}
                            <option value="{{ key }}">{{ model.model.Meta.verbose_name_plural|default:key }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">逻辑关系</label>
                        <select id="logicOperator" class="form-select">
                            <option value="AND">AND (且)</option>
                            <option value="OR">OR (或)</option>
                        </select>
                    </div>
                </div>

                <!-- 搜索条件 -->
                <div id="searchConditions">
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-info-circle fa-2x mb-2"></i>
                        <p>请先选择搜索模型，然后添加搜索条件</p>
                    </div>
                </div>

                <!-- 添加条件按钮 -->
                <div class="text-center mt-3">
                    <button type="button" class="btn btn-outline-primary" onclick="addCondition()" id="addConditionBtn" disabled>
                        <i class="fas fa-plus"></i> 添加条件
                    </button>
                </div>
            </div>

            <!-- 搜索结果 -->
            <div id="searchResults" class="search-results" style="display: none;">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5><i class="fas fa-list"></i> 搜索结果</h5>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-success" onclick="exportResults('excel')">
                            <i class="fas fa-file-excel"></i> Excel
                        </button>
                        <button type="button" class="btn btn-outline-info" onclick="exportResults('csv')">
                            <i class="fas fa-file-csv"></i> CSV
                        </button>
                        <button type="button" class="btn btn-outline-danger" onclick="exportResults('pdf')">
                            <i class="fas fa-file-pdf"></i> PDF
                        </button>
                    </div>
                </div>
                
                <div id="resultsContainer">
                    <!-- 搜索结果将在这里显示 -->
                </div>
                
                <!-- 分页 -->
                <nav id="resultsPagination" style="display: none;">
                    <ul class="pagination justify-content-center">
                        <!-- 分页按钮将在这里生成 -->
                    </ul>
                </nav>
            </div>
        </div>

        <!-- 侧边栏 -->
        <div class="col-md-4">
            <!-- 快速操作 -->
            <div class="quick-actions mb-4">
                <h6><i class="fas fa-bolt"></i> 快速操作</h6>
                <div class="d-grid gap-2">
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="saveAsTemplate()">
                        <i class="fas fa-save"></i> 保存为模板
                    </button>
                    <button type="button" class="btn btn-outline-info btn-sm" onclick="saveSearch()">
                        <i class="fas fa-bookmark"></i> 保存搜索
                    </button>
                    <button type="button" class="btn btn-outline-warning btn-sm" onclick="createAlert()">
                        <i class="fas fa-bell"></i> 创建预警
                    </button>
                </div>
            </div>

            <!-- 搜索历史 -->
            <div class="card">
                <div class="card-header">
                    <h6><i class="fas fa-history"></i> 搜索历史</h6>
                </div>
                <div class="card-body">
                    {% if search_history %}
                        {% for history in search_history %}
                        <div class="search-history-item" onclick="loadSearchHistory({{ history.id }})">
                            <div class="fw-bold">{{ history.search_name }}</div>
                            <small class="text-muted">
                                {{ history.search_type }} - {{ history.created_at|date:"m-d H:i" }}
                            </small>
                        </div>
                        {% endfor %}
                    {% else %}
                        <div class="text-center text-muted">
                            <i class="fas fa-history fa-2x mb-2"></i>
                            <p>暂无搜索历史</p>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 保存模板模态框 -->
<div class="modal fade" id="saveTemplateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">保存搜索模板</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="saveTemplateForm">
                    <div class="mb-3">
                        <label class="form-label">模板名称</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">模板描述</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_public" id="isPublic">
                        <label class="form-check-label" for="isPublic">
                            公开模板（其他用户可以使用）
                        </label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitSaveTemplate()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 保存搜索模态框 -->
<div class="modal fade" id="saveSearchModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">保存搜索</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="saveSearchForm">
                    <div class="mb-3">
                        <label class="form-label">搜索名称</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="enable_notifications" id="enableNotifications">
                        <label class="form-check-label" for="enableNotifications">
                            启用通知
                        </label>
                    </div>
                    <div class="mb-3" id="notificationFrequency" style="display: none;">
                        <label class="form-label">通知频率</label>
                        <select class="form-select" name="notification_frequency">
                            <option value="daily">每日</option>
                            <option value="weekly">每周</option>
                            <option value="monthly">每月</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitSaveSearch()">保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 全局变量
let currentModel = '';
let modelFields = {};
let conditionCounter = 0;
let currentSearchParams = {};
let currentResults = [];

// 操作符配置
const operators = {
    {% for op in operators %}
    '{{ op.value }}': '{{ op.label }}',
    {% endfor %}
};

// 字段类型对应的操作符
const fieldOperators = {
    'text': ['equals', 'not_equals', 'contains', 'not_contains', 'starts_with', 'ends_with', 'is_null', 'is_not_null'],
    'number': ['equals', 'not_equals', 'gt', 'gte', 'lt', 'lte', 'between', 'is_null', 'is_not_null'],
    'date': ['equals', 'not_equals', 'gt', 'gte', 'lt', 'lte', 'date_range', 'is_null', 'is_not_null'],
    'choice': ['equals', 'not_equals', 'in', 'is_null', 'is_not_null']
};

// 模型改变事件
function onModelChange() {
    const modelSelect = document.getElementById('searchModel');
    currentModel = modelSelect.value;
    
    if (currentModel) {
        loadModelFields(currentModel);
        document.getElementById('addConditionBtn').disabled = false;
        clearConditions();
    } else {
        document.getElementById('addConditionBtn').disabled = true;
        clearConditions();
    }
}

// 加载模型字段
function loadModelFields(modelName) {
    fetch(`/assets/search/model-fields/${modelName}/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                modelFields = data.fields;
            } else {
                showAlert('error', data.message);
            }
        })
        .catch(error => {
            showAlert('error', '加载字段失败: ' + error.message);
        });
}

// 添加搜索条件
function addCondition() {
    if (!currentModel || !modelFields) {
        showAlert('warning', '请先选择搜索模型');
        return;
    }
    
    conditionCounter++;
    const conditionId = `condition_${conditionCounter}`;
    
    const conditionHtml = `
        <div class="condition-row" id="${conditionId}">
            <i class="fas fa-times remove-condition" onclick="removeCondition('${conditionId}')"></i>
            
            <div class="row">
                <div class="col-md-4">
                    <label class="form-label">字段</label>
                    <select class="form-select field-select" onchange="onFieldChange('${conditionId}')">
                        <option value="">请选择字段</option>
                        ${Object.entries(modelFields).map(([key, field]) => 
                            `<option value="${key}" data-type="${field.type}">${field.label}<span class="field-type-indicator">(${field.type})</span></option>`
                        ).join('')}
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">操作符</label>
                    <select class="form-select operator-select" disabled>
                        <option value="">请选择操作符</option>
                    </select>
                </div>
                <div class="col-md-5">
                    <label class="form-label">值</label>
                    <div class="value-input">
                        <input type="text" class="form-control" placeholder="请输入值" disabled>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    const conditionsContainer = document.getElementById('searchConditions');
    
    // 如果是第一个条件，清空提示信息
    if (conditionCounter === 1) {
        conditionsContainer.innerHTML = '';
    }
    
    // 如果不是第一个条件，添加逻辑操作符
    if (conditionCounter > 1) {
        const logicOperator = document.getElementById('logicOperator').value;
        conditionsContainer.innerHTML += `
            <div class="logic-operator">
                <span class="badge bg-primary">${logicOperator}</span>
            </div>
        `;
    }
    
    conditionsContainer.innerHTML += conditionHtml;
}

// 字段改变事件
function onFieldChange(conditionId) {
    const condition = document.getElementById(conditionId);
    const fieldSelect = condition.querySelector('.field-select');
    const operatorSelect = condition.querySelector('.operator-select');
    const valueInput = condition.querySelector('.value-input');
    
    const selectedOption = fieldSelect.selectedOptions[0];
    if (!selectedOption || !selectedOption.value) {
        operatorSelect.disabled = true;
        valueInput.querySelector('input').disabled = true;
        return;
    }
    
    const fieldType = selectedOption.dataset.type;
    const availableOperators = fieldOperators[fieldType] || [];
    
    // 更新操作符选项
    operatorSelect.innerHTML = '<option value="">请选择操作符</option>';
    availableOperators.forEach(op => {
        operatorSelect.innerHTML += `<option value="${op}">${operators[op]}</option>`;
    });
    
    operatorSelect.disabled = false;
    operatorSelect.onchange = () => onOperatorChange(conditionId);
}

// 操作符改变事件
function onOperatorChange(conditionId) {
    const condition = document.getElementById(conditionId);
    const operatorSelect = condition.querySelector('.operator-select');
    const valueInput = condition.querySelector('.value-input');
    const fieldSelect = condition.querySelector('.field-select');
    
    const operator = operatorSelect.value;
    const fieldType = fieldSelect.selectedOptions[0].dataset.type;
    
    if (!operator) {
        valueInput.querySelector('input').disabled = true;
        return;
    }
    
    // 根据操作符类型生成不同的输入控件
    let inputHtml = '';
    
    if (operator === 'between') {
        inputHtml = `
            <div class="row">
                <div class="col-6">
                    <input type="${fieldType === 'date' ? 'date' : 'number'}" class="form-control" placeholder="最小值">
                </div>
                <div class="col-6">
                    <input type="${fieldType === 'date' ? 'date' : 'number'}" class="form-control" placeholder="最大值">
                </div>
            </div>
        `;
    } else if (operator === 'date_range') {
        inputHtml = `
            <div class="row">
                <div class="col-6">
                    <input type="date" class="form-control" placeholder="开始日期">
                </div>
                <div class="col-6">
                    <input type="date" class="form-control" placeholder="结束日期">
                </div>
            </div>
        `;
    } else if (operator === 'in') {
        inputHtml = `
            <textarea class="form-control" rows="2" placeholder="请输入多个值，用逗号分隔"></textarea>
        `;
    } else if (operator === 'is_null' || operator === 'is_not_null') {
        inputHtml = `
            <input type="text" class="form-control" value="无需输入值" disabled>
        `;
    } else if (fieldType === 'choice') {
        // 这里应该根据字段的choices生成选项
        inputHtml = `
            <select class="form-select">
                <option value="">请选择值</option>
                <!-- 选项应该从模型字段配置中获取 -->
            </select>
        `;
    } else {
        const inputType = fieldType === 'number' ? 'number' : 
                         fieldType === 'date' ? 'date' : 'text';
        inputHtml = `
            <input type="${inputType}" class="form-control" placeholder="请输入值">
        `;
    }
    
    valueInput.innerHTML = inputHtml;
}

// 移除搜索条件
function removeCondition(conditionId) {
    const condition = document.getElementById(conditionId);
    const conditionsContainer = document.getElementById('searchConditions');
    
    // 移除条件
    condition.remove();
    
    // 重新构建逻辑操作符
    rebuildLogicOperators();
    
    // 如果没有条件了，显示提示信息
    if (conditionsContainer.children.length === 0) {
        conditionsContainer.innerHTML = `
            <div class="text-center text-muted py-4">
                <i class="fas fa-info-circle fa-2x mb-2"></i>
                <p>请添加搜索条件</p>
            </div>
        `;
    }
}

// 重建逻辑操作符
function rebuildLogicOperators() {
    const conditionsContainer = document.getElementById('searchConditions');
    const conditions = conditionsContainer.querySelectorAll('.condition-row');
    const logicOperators = conditionsContainer.querySelectorAll('.logic-operator');
    
    // 移除所有逻辑操作符
    logicOperators.forEach(op => op.remove());
    
    // 在条件之间重新插入逻辑操作符
    if (conditions.length > 1) {
        const logicOperator = document.getElementById('logicOperator').value;
        
        for (let i = 1; i < conditions.length; i++) {
            const logicDiv = document.createElement('div');
            logicDiv.className = 'logic-operator';
            logicDiv.innerHTML = `<span class="badge bg-primary">${logicOperator}</span>`;
            
            conditions[i].parentNode.insertBefore(logicDiv, conditions[i]);
        }
    }
}

// 清空搜索条件
function clearConditions() {
    const conditionsContainer = document.getElementById('searchConditions');
    conditionsContainer.innerHTML = `
        <div class="text-center text-muted py-4">
            <i class="fas fa-info-circle fa-2x mb-2"></i>
            <p>请先选择搜索模型，然后添加搜索条件</p>
        </div>
    `;
    conditionCounter = 0;
}

// 清空搜索
function clearSearch() {
    document.getElementById('searchModel').value = '';
    currentModel = '';
    modelFields = {};
    clearConditions();
    document.getElementById('addConditionBtn').disabled = true;
    document.getElementById('searchResults').style.display = 'none';
}

// 执行搜索
function executeSearch() {
    if (!currentModel) {
        showAlert('warning', '请选择搜索模型');
        return;
    }
    
    const conditions = collectSearchConditions();
    if (conditions.length === 0) {
        showAlert('warning', '请添加至少一个搜索条件');
        return;
    }
    
    const searchParams = {
        model: currentModel,
        params: {
            conditions: conditions,
            logic: document.getElementById('logicOperator').value
        }
    };
    
    currentSearchParams = searchParams;
    
    showLoading('正在搜索...');
    
    fetch('/assets/search/execute/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(searchParams)
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.success) {
            displaySearchResults(data.results, data.pagination);
        } else {
            showAlert('error', data.message);
        }
    })
    .catch(error => {
        hideLoading();
        showAlert('error', '搜索失败: ' + error.message);
    });
}

// 收集搜索条件
function collectSearchConditions() {
    const conditions = [];
    const conditionRows = document.querySelectorAll('.condition-row');
    
    conditionRows.forEach(row => {
        const fieldSelect = row.querySelector('.field-select');
        const operatorSelect = row.querySelector('.operator-select');
        const valueInputs = row.querySelectorAll('.value-input input, .value-input select, .value-input textarea');
        
        if (fieldSelect.value && operatorSelect.value) {
            let value = null;
            
            if (operatorSelect.value === 'between' || operatorSelect.value === 'date_range') {
                const inputs = row.querySelectorAll('.value-input input');
                if (inputs.length === 2 && inputs[0].value && inputs[1].value) {
                    value = [inputs[0].value, inputs[1].value];
                }
            } else if (operatorSelect.value === 'in') {
                const textarea = row.querySelector('.value-input textarea');
                if (textarea && textarea.value) {
                    value = textarea.value.split(',').map(v => v.trim()).filter(v => v);
                }
            } else if (operatorSelect.value === 'is_null' || operatorSelect.value === 'is_not_null') {
                value = true;
            } else {
                const input = valueInputs[0];
                if (input && input.value) {
                    value = input.value;
                }
            }
            
            if (value !== null) {
                conditions.push({
                    field: fieldSelect.value,
                    operator: operatorSelect.value,
                    value: value
                });
            }
        }
    });
    
    return conditions;
}

// 显示搜索结果
function displaySearchResults(results, pagination) {
    currentResults = results;
    
    const resultsContainer = document.getElementById('resultsContainer');
    const searchResults = document.getElementById('searchResults');
    
    if (results.length === 0) {
        resultsContainer.innerHTML = `
            <div class="text-center text-muted py-4">
                <i class="fas fa-search fa-3x mb-3"></i>
                <h5>未找到匹配的结果</h5>
                <p>请尝试调整搜索条件</p>
            </div>
        `;
    } else {
        let html = `
            <div class="mb-3">
                <span class="badge bg-success">找到 ${pagination.total_count} 条结果</span>
            </div>
        `;
        
        results.forEach(result => {
            html += `
                <div class="result-item">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="flex-grow-1">
                            <h6><a href="${result.detail_url}" target="_blank">${result.display_name}</a></h6>
                            <div class="row">
                                ${Object.entries(result).filter(([key, value]) => 
                                    !['id', 'display_name', 'detail_url'].includes(key) && value
                                ).map(([key, value]) => 
                                    `<div class="col-md-6"><small class="text-muted">${key}:</small> ${value}</div>`
                                ).join('')}
                            </div>
                        </div>
                        <div class="btn-group btn-group-sm">
                            <a href="${result.detail_url}" class="btn btn-outline-primary btn-sm" target="_blank">
                                <i class="fas fa-eye"></i>
                            </a>
                        </div>
                    </div>
                </div>
            `;
        });
        
        resultsContainer.innerHTML = html;
        
        // 显示分页
        displayPagination(pagination);
    }
    
    searchResults.style.display = 'block';
}

// 显示分页
function displayPagination(pagination) {
    const paginationContainer = document.getElementById('resultsPagination');
    
    if (pagination.total_pages <= 1) {
        paginationContainer.style.display = 'none';
        return;
    }
    
    let html = '';
    
    // 上一页
    if (pagination.has_previous) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="searchPage(${pagination.current_page - 1})">上一页</a></li>`;
    }
    
    // 页码
    const startPage = Math.max(1, pagination.current_page - 2);
    const endPage = Math.min(pagination.total_pages, pagination.current_page + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        const activeClass = i === pagination.current_page ? 'active' : '';
        html += `<li class="page-item ${activeClass}"><a class="page-link" href="#" onclick="searchPage(${i})">${i}</a></li>`;
    }
    
    // 下一页
    if (pagination.has_next) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="searchPage(${pagination.current_page + 1})">下一页</a></li>`;
    }
    
    paginationContainer.querySelector('.pagination').innerHTML = html;
    paginationContainer.style.display = 'block';
}

// 搜索指定页
function searchPage(page) {
    const searchParams = {
        ...currentSearchParams,
        page: page
    };
    
    showLoading('正在加载...');
    
    fetch('/assets/search/execute/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(searchParams)
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.success) {
            displaySearchResults(data.results, data.pagination);
        } else {
            showAlert('error', data.message);
        }
    })
    .catch(error => {
        hideLoading();
        showAlert('error', '加载失败: ' + error.message);
    });
}

// 导出结果
function exportResults(format) {
    if (!currentSearchParams || currentResults.length === 0) {
        showAlert('warning', '没有可导出的结果');
        return;
    }
    
    const exportParams = {
        ...currentSearchParams,
        format: format
    };
    
    showLoading('正在导出...');
    
    fetch('/assets/search/export/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(exportParams)
    })
    .then(response => {
        hideLoading();
        if (response.ok) {
            // 下载文件
            return response.blob();
        } else {
            throw new Error('导出失败');
        }
    })
    .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `search_results_${new Date().getTime()}.${format}`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
    })
    .catch(error => {
        hideLoading();
        showAlert('error', '导出失败: ' + error.message);
    });
}

// 保存为模板
function saveAsTemplate() {
    if (!currentModel || conditionCounter === 0) {
        alert('请先选择模型并添加搜索条件');
        return;
    }
    
    const modal = new bootstrap.Modal(document.getElementById('saveTemplateModal'));
    modal.show();
}

// 显示搜索帮助
function showSearchHelp() {
    const helpContent = `
        <div class="modal fade" id="searchHelpModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="fas fa-question-circle me-2"></i>搜索帮助</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <h6>搜索操作说明：</h6>
                        <ul>
                            <li><strong>选择模型：</strong>首先选择要搜索的数据类型（资产、供应商、合同等）</li>
                            <li><strong>添加条件：</strong>点击"添加条件"按钮，设置字段、操作符和值</li>
                            <li><strong>逻辑关系：</strong>选择AND（且）或OR（或）来组合多个条件</li>
                            <li><strong>执行搜索：</strong>点击"执行搜索"按钮查看结果</li>
                        </ul>
                        <h6>操作符说明：</h6>
                        <ul>
                            <li><strong>等于：</strong>精确匹配</li>
                            <li><strong>包含：</strong>模糊匹配，包含指定文本</li>
                            <li><strong>大于/小于：</strong>用于数值和日期比较</li>
                            <li><strong>范围：</strong>在指定范围内</li>
                        </ul>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 移除已存在的帮助模态框
    const existingModal = document.getElementById('searchHelpModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // 添加新的帮助模态框
    document.body.insertAdjacentHTML('beforeend', helpContent);
    const modal = new bootstrap.Modal(document.getElementById('searchHelpModal'));
    modal.show();
}

// 显示搜索模板
function showSearchTemplates() {
    const templateContent = `
        <div class="modal fade" id="searchTemplatesModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="fas fa-layer-group me-2"></i>搜索模板</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6>我的模板</h6>
                                <div class="list-group">
                                    <div class="list-group-item text-muted text-center py-3">
                                        <i class="fas fa-folder-open fa-2x mb-2"></i>
                                        <p class="mb-0">暂无保存的模板</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6>公共模板</h6>
                                <div class="list-group">
                                    <a href="#" class="list-group-item list-group-item-action" onclick="loadTemplate('asset_basic')">
                                        <div class="d-flex w-100 justify-content-between">
                                            <h6 class="mb-1">基础资产查询</h6>
                                            <small>系统</small>
                                        </div>
                                        <p class="mb-1">查询基本资产信息</p>
                                    </a>
                                    <a href="#" class="list-group-item list-group-item-action" onclick="loadTemplate('maintenance_overdue')">
                                        <div class="d-flex w-100 justify-content-between">
                                            <h6 class="mb-1">逾期维修查询</h6>
                                            <small>系统</small>
                                        </div>
                                        <p class="mb-1">查询逾期未完成的维修记录</p>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 移除已存在的模板模态框
    const existingModal = document.getElementById('searchTemplatesModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // 添加新的模板模态框
    document.body.insertAdjacentHTML('beforeend', templateContent);
    const modal = new bootstrap.Modal(document.getElementById('searchTemplatesModal'));
    modal.show();
}

// 加载搜索模板
function loadTemplate(templateId) {
    // 这里可以根据模板ID加载预定义的搜索条件
    console.log('Loading template:', templateId);
    // 关闭模板模态框
    const modal = bootstrap.Modal.getInstance(document.getElementById('searchTemplatesModal'));
    if (modal) {
        modal.hide();
    }
}

// 提交保存模板
function submitSaveTemplate() {
    const form = document.getElementById('saveTemplateForm');
    const formData = new FormData(form);
    
    const templateData = {
        name: formData.get('name'),
        description: formData.get('description'),
        model: currentModel,
        params: {
            conditions: collectSearchConditions(),
            logic: document.getElementById('logicOperator').value
        },
        is_public: formData.has('is_public')
    };
    
    fetch('/assets/search/save-template/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(templateData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', data.message);
            bootstrap.Modal.getInstance(document.getElementById('saveTemplateModal')).hide();
            form.reset();
        } else {
            showAlert('error', data.message);
        }
    })
    .catch(error => {
        showAlert('error', '保存失败: ' + error.message);
    });
}

// 保存搜索
function saveSearch() {
    if (!currentModel || collectSearchConditions().length === 0) {
        showAlert('warning', '请先构建搜索条件');
        return;
    }
    
    const modal = new bootstrap.Modal(document.getElementById('saveSearchModal'));
    modal.show();
    
    // 通知设置切换
    document.getElementById('enableNotifications').onchange = function() {
        const notificationDiv = document.getElementById('notificationFrequency');
        notificationDiv.style.display = this.checked ? 'block' : 'none';
    };
}

// 提交保存搜索
function submitSaveSearch() {
    const form = document.getElementById('saveSearchForm');
    const formData = new FormData(form);
    
    const searchData = {
        name: formData.get('name'),
        model: currentModel,
        params: {
            conditions: collectSearchConditions(),
            logic: document.getElementById('logicOperator').value
        },
        enable_notifications: formData.has('enable_notifications'),
        notification_frequency: formData.get('notification_frequency')
    };
    
    // 这里应该调用保存搜索的API
    showAlert('info', '保存搜索功能正在开发中');
    bootstrap.Modal.getInstance(document.getElementById('saveSearchModal')).hide();
}

// 创建预警
function createAlert() {
    showAlert('info', '创建预警功能正在开发中');
}

// 加载搜索历史
function loadSearchHistory(historyId) {
    showAlert('info', '加载搜索历史功能正在开发中');
}

// 工具函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function showLoading(message) {
    const loading = document.createElement('div');
    loading.id = 'loading-overlay';
    loading.className = 'loading-overlay';
    loading.innerHTML = `
        <div class="text-center">
            <div class="spinner-border text-primary mb-2"></div>
            <div>${message}</div>
        </div>
    `;
    document.body.appendChild(loading);
}

function hideLoading() {
    const loading = document.getElementById('loading-overlay');
    if (loading) {
        loading.remove();
    }
}

function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 
                     type === 'warning' ? 'alert-warning' :
                     type === 'info' ? 'alert-info' : 'alert-danger';
    
    const alert = document.createElement('div');
    alert.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
    alert.style.top = '20px';
    alert.style.right = '20px';
    alert.style.zIndex = '9999';
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alert);
    
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, 5000);
}
</script>
{% endblock %}